package cn.im.qywx.system;

import cn.im.qywx.model.Department;
import cn.im.qywx.model.UserInfo;
import cn.im.qywx.queue.TokenQueue;
import cn.im.qywx.util.JsonUtils;
import cn.im.qywx.view.ImWxToken;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * 系统初始化加载
 */
@Component
@Slf4j
public class SystemInit implements CommandLineRunner{

	@Autowired
	RestTemplate restTemplate;

	@Override
	public void run(String... args) throws Exception {
		log.info("init by CommandLineRunner===");
		TokenQueue.tokenMap.put(SystemParams.AGENTID_MEETING, new ImWxToken(SystemParams.AGENTID_MEETING,SystemParams.SECRET_MEETING));
		//获取部门人员列表
		getDepartments();
	}

	/** 获取部门人员列表(用的会议室应用)(每16个小时刷新一次)
	 */
	private void getDepartments (){
		final HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		new Thread(new Runnable(){
			public void run() {
				while(true){
					String url = SystemParams.URL_DEPT+TokenQueue.getToken(SystemParams.AGENTID_MEETING);
					//获取部门列表
					Map<String,Object> map = JsonUtils.json2Map(restTemplate.getForObject(url,String.class));
					if(map==null || (!"0.0".equals(map.get("errcode")+"") && !"0".equals(map.get("errcode")+""))){
						try {Thread.sleep(1000*60*30);} catch (InterruptedException e) {e.printStackTrace();}
						continue;
					}
					boolean needContinue=false;
					List<Map<String,Object>> userList = new ArrayList<Map<String,Object>>();

					//遍历加载数据
					Map<Integer, Department> id_departments = new HashMap<Integer,Department>();
					List<Department> departments = new ArrayList<Department>();
					for(Map<String,Object> depMap : (List<Map<String,Object>>)map.get("department")){
						Department dep = new Department();
						dep.setId(Math.round(Float.valueOf(depMap.get("id")+"")));
						dep.setParentId(Math.round(Float.valueOf(depMap.get("parentid")+"")));
						dep.setOrder(Math.round(Float.valueOf(depMap.get("order")+"")));
						dep.setName(String.valueOf(depMap.get("name")));
						departments.add(dep);
						id_departments.put(dep.getId(), dep);

						//通过部门获取成员列表
						Map<String,Object> mapUser = JsonUtils.json2Map(restTemplate.getForObject(SystemParams.URL_USER+"list?department_id="+dep.getId()+"&fetch_child=0&access_token="+ TokenQueue.getToken(SystemParams.AGENTID_MEETING),String.class));
						if(mapUser==null || (!"0.0".equals(mapUser.get("errcode")+"") && !"0".equals(mapUser.get("errcode")+""))){
							log.info("获取成员列表失败:"+(mapUser==null?"超时":mapUser.get("errcode")));
							try {Thread.sleep(1000*60*30);} catch (InterruptedException e) {e.printStackTrace();}
							needContinue=true;
							break;
						}
						userList.addAll((List<Map<String,Object>>)mapUser.get("userlist"));
					}

					if(needContinue){
						continue;
					}

					Set<String> exists = new HashSet<String>();

					//解析并存放数据
					for(Map<String,Object> userMap : userList){
						if(exists.contains(String.valueOf(userMap.get("userid")))){
							continue;
						}
						exists.add(String.valueOf(userMap.get("userid")));

						UserInfo user = new UserInfo();
						user.setWxno(String.valueOf(userMap.get("userid")));
						user.setName(String.valueOf(userMap.get("name")));
						user.setAvatar(String.valueOf(userMap.get("avatar")));
						user.setNamePy(PinyinHelper.toHanyuPinyinString(user.getName(),format , ",,"));
						if(user.getNamePy().indexOf(",,")!=-1){
							String[] ps = user.getNamePy().split(",,");
							user.setNamePy(user.getNamePy().replace(",,", ""));
							StringBuilder sb = new StringBuilder();
							for(String p : ps){
								if(p.length()>0)
									sb.append(p.charAt(0));
							}
							user.setNamePyFirst(sb.toString());
						}else{
							user.setNamePyFirst("");
						}
						if(!StringUtils.isEmpty(user.getAvatar())){
							if(user.getAvatar().equals("/0"))
								user.setAvatar("");
							else if(user.getAvatar().endsWith("/"))
								user.setAvatar(user.getAvatar()+"100");
							else if(user.getAvatar().endsWith("/0"))
								user.setAvatar(user.getAvatar().substring(0, user.getAvatar().length()-2)+"/100");
						}
						List<Double> pIdsf = (List<Double>)userMap.get("department");
						List<Integer> pids = new ArrayList<Integer>();
						for(Double f : pIdsf){
							int id = (int)Math.round(f);
							pids.add(id);
							if(id_departments.containsKey(id)){
								id_departments.get(id).getUsers().add(user);
							}
						}
//						user.setDepartmentId(pids);
					}

					if(departments.size()>0){
						SystemParams.departments=departments;
						log.info(JsonUtils.obj2json(SystemParams.departments));
					}else{
						log.info("没有获取到部门列表");
					}
					try {Thread.sleep(1000*60*60*16);} catch (InterruptedException e) {e.printStackTrace();}
				}
			}
		}).start();
	}

}
